package com.atguigu.tingshu.common.date;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.deser.std.DateDeserializers;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

@Configuration
public class CustomerDateHandler implements Jackson2ObjectMapperBuilderCustomizer {
    @Override
    public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(Date.class,new DateSerializer(){
            // 重写DateSerializer的序列化方法，处理时区
            @Override
            public void serialize(Date value, JsonGenerator g, SerializerProvider provider) throws IOException {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                String format = simpleDateFormat.format(value);
                g.writeString(format);
            }
        });
        javaTimeModule.addDeserializer(Date.class,new DateDeserializers.DateDeserializer(){
            @Override
            public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                try {
                    String text = p.getText();
                    return simpleDateFormat.parse(text);
                } catch (ParseException e) {
                    throw new GuiguException(201, "日期格式不正确");
                }
            }
        });
        // 将时间模式注册到Jackson2ObjectMapperBuilder中
        jacksonObjectMapperBuilder.modulesToInstall(javaTimeModule);
    }
}
